package com.sosee.cgfw.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.sosee.cgfw.R;
import com.sosee.cgfw.adapter.FragmentAdapter;
import com.sosee.cgfw.fragment.PicFragment;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.sosee.cgfw.utils.Utils;
import com.lidroid.xutils.BitmapUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import cn.sharesdk.wechat.utils.WechatHelper;

/**
 * Created by Thinkpad on 2016/1/25.
 * //秀场自拍activity
 */
public class ShowYourSelfActivity extends FragmentActivity implements ViewPager.OnPageChangeListener {
    private SurfaceView sv;//显示界面
    private boolean isPreview;//是否正在预览
    private int cameraPosition = 1;//0代表前置摄像头，1代表后置摄像头
    private RelativeLayout fl;//拍照界面
    private RelativeLayout rl_menu;//底部拍照菜单
    private RelativeLayout rl_share_menu;//底部分享菜单
    private RelativeLayout fl_new;//合成的照片
    private ImageView ig_new;//照片
    private RelativeLayout rl_share_choose;//分享选择菜单
    private String imgUrl_share;//要分享的图片路径
    private Canvas mCanvans;
    private BitmapUtils bitmapUtils;
    private ViewPager vp;//相框选择
    private FragmentAdapter mAdapter;
    private List<Fragment> flist;//fragment集合
    private int position=0;//记录用户选择相框位置


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_showyourself);
        initUI();
        ShareSDK.initSDK(this);
        bitmapUtils=new BitmapUtils(this);
    }
    private int wid;
    private int hei;

    //初始化ui
    public void initUI() {
        WindowManager wm=getWindowManager();


        fl = (RelativeLayout) findViewById(R.id.fl);
         wid=fl.getWidth();
         hei=fl.getHeight();
        sv = (SurfaceView) findViewById(R.id.sv);
        initViewPager();

//        sv.getHolder().setFixedSize(wid, hei);
        if(Build.VERSION.SDK_INT < 11){
            sv.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        sv.getHolder().addCallback(new SurfaceCallback());
        rl_menu = (RelativeLayout) findViewById(R.id.rl_menu);
        rl_share_menu = (RelativeLayout) findViewById(R.id.rl_share_menu);
        fl_new = (RelativeLayout) findViewById(R.id.fl_new);
        ig_new = (ImageView) findViewById(R.id.ig_new);
        rl_share_choose = (RelativeLayout) findViewById(R.id.rl_share_choose);
        rl_share_choose.setVisibility(View.INVISIBLE);
    }





    //初始化相框
    public void initViewPager(){
        vp= (ViewPager) findViewById(R.id.vp);
        mAdapter=new FragmentAdapter(getSupportFragmentManager());
        flist=new ArrayList<Fragment>();
        PicFragment f1=new PicFragment();
        Bundle bundle=new Bundle();
        bundle.putString("flag", "0");
        f1.setArguments(bundle);
        PicFragment f2=new PicFragment();
        Bundle b2=new Bundle();
        b2.putString("flag", "1");
        f2.setArguments(b2);

        PicFragment f3=new PicFragment();
        Bundle b3=new Bundle();
        b3.putString("flag","2");
        f3.setArguments(b3);
        flist.add(f1);
        flist.add(f2);
        flist.add(f3);
        mAdapter.setList(flist);
        vp.setAdapter(mAdapter);
        vp.setOnPageChangeListener(this);
    }


    private Camera camera;//照相机

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        this.position=position;

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    public class SurfaceCallback implements SurfaceHolder.Callback {
        int PreviewWidth = 0;
        int PreviewHeight = 0;
        int picWidth = 0;
        int picHeight = 0;


        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            //testsvn

            try {
                if(!isPreview){
                    camera = Camera.open();//打开硬件摄像头，这里导包得时候一定要注意是android.hardware.Camera
                }
//                camera.setDisplayOrientation(90);//设置预览时方向
                WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);//得到窗口管理器
                Display display = wm.getDefaultDisplay();//得到当前屏幕
                Camera.Parameters parameters = camera.getParameters();//得到摄像头的参数
                Camera.Size pictureSize = parameters.getPictureSize();
                LogUtils.log_E("相机参数："+pictureSize.height+":::::"+pictureSize.width);
                List<Camera.Size> sizeList = parameters.getSupportedPreviewSizes();
                List<Camera.Size> pList = parameters.getSupportedPictureSizes();





//                //获取合适的图片尺寸
//                if (pList.size() > 1) {
//                    for (int i = 0; i < pList.size(); i++) {
//                        if (pList.get(i).width >= picWidth
//                                && pList.get(i).height >= picHeight) {
//                            picWidth = pList.get(i).width;
//                            picHeight = pList.get(i).height;
//                            break;
//                        }
//                    }
//                }
//                //获取合适的预览尺寸
//                if (sizeList.size() > 1) {
//                    Iterator<Camera.Size> itor = sizeList.iterator();
//                    while (itor.hasNext()) {
//                        Camera.Size cur = itor.next();
//                        if (cur.width >= PreviewWidth
//                                && cur.height >= PreviewHeight) {
//                            PreviewWidth = cur.width;
//                            PreviewHeight = cur.height;
//                            break;
//                        }
//                    }
//                }
//                parameters.setPreviewSize(PreviewWidth, PreviewHeight);//设置预览照片的大小
//                parameters.setPreviewFpsRange(10,20);//设置每秒3帧





                parameters.setPreviewFrameRate(3);
                parameters.getPictureFormat();
                LogUtils.log_E("获取图片格式：：：：：：：" + parameters.getPreviewSize().width+":"+parameters.getPreviewSize().height);
                parameters.setPictureFormat(PixelFormat.JPEG);//设置照片的格式
                parameters.setJpegQuality(100);//设置照片的质量


//                parameters.setPictureSize(wid, hei);//设置照片的大小，默认是和     屏幕一样大
//                parameters.setPictureSize(sv.getWidth(),sv.getHeight());


                camera.setParameters(parameters);
                camera.setPreviewDisplay(sv.getHolder());//通过SurfaceView显示取景画面
                if(!isPreview){
                    camera.startPreview();//开始预览
                }
                isPreview = true;//设置是否预览参数为真
            } catch (IOException e) {
                LogUtils.log_E(e.toString());
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
            if(isPreview){

            }
            camera.autoFocus(new Camera.AutoFocusCallback() {
                @Override
                public void onAutoFocus(boolean success, Camera camera) {
                    if(success){
                        initCamera();//实现相机的参数初始化
                        camera.cancelAutoFocus();//只有加上了这一句，才会自动对焦。
                    }
                }

            });

        }


        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            if (camera != null) {
                if (isPreview) {//如果正在预览
                    camera.stopPreview();
                    isPreview = false;
                    camera.release();
                }
            }
        }

    }

//    //按钮点击事件
//    public void onclick(View view) {//处理按键事件
//        if (camera != null) {
//            //拍照
////            if (view.getId() == R.id.paizhao) {
////                mCanvans=sv.getHolder().lockCanvas();
////                Bitmap bitmap = Bitmap.createBitmap(sv.getWidth(), sv.getHeight(), Bitmap.Config.ARGB_8888);
////                Canvas bitCanvas = new Canvas(bitmap);
//////                bitmap.(bitCanvas);//在自己创建的canvas上画
////
//////保存截屏图片
////                File file = new File(Constans.PIC_SHARE+ "hu"+System.currentTimeMillis() + ".jpg");
////                FileOutputStream fos;
////                try {
////                    fos = new FileOutputStream(file);
////                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
////                    fos.close();
////                } catch (Exception e) {
////                    LogUtils.log_E("测试截屏异常："+e.getMessage());
////                    e.printStackTrace();
////                }
//
//                camera.takePicture(null, null, new TakePictureCallback());
//                //取消 返回
//            } else {
//                //开启闪光灯
////                if (view.getId() == R.id.shanguang) {
//                    Camera.Parameters parameter;
//
//                    parameter = camera.getParameters();
//
//
//                    String status=parameter.getFlashMode();
//                    if(status.equals(Camera.Parameters.FLASH_MODE_TORCH)){
//                        parameter.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
//
//                    }else{
//                        parameter.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
//
//                    }
//
//
//                    camera.setParameters(parameter);
//
//                } else {
//                    //切换前后摄像头
//                    int cameraCount = 0;
//                    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
//                    cameraCount = Camera.getNumberOfCameras();//得到摄像头的个数
//
//                    for (int i = 0; i < cameraCount; i++) {
//                        Camera.getCameraInfo(i, cameraInfo);//得到每一个摄像头的信息
//                        if (cameraPosition == 1) {
//                            //现在是后置，变更为前置
//                            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {//代表摄像头的方位，CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
//                                camera.stopPreview();//停掉原来摄像头的预览
//                                camera.release();//释放资源
//                                camera = null;//取消原来摄像头
//                                camera = Camera.open(i);//打开当前选中的摄像头
//                                camera.setDisplayOrientation(90);
//                                try {
//                                    camera.setPreviewDisplay(sv.getHolder());//通过surfaceview显示取景画面
//                                } catch (IOException e) {
//                                    // TODO Auto-generated catch block
//                                    e.printStackTrace();
//                                }
//                                camera.startPreview();//开始预览
//                                cameraPosition = 0;
//                                break;
//                            }
//                        } else {
//                            //现在是前置， 变更为后置
//                            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {//代表摄像头的方位，CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
//                                camera.stopPreview();//停掉原来摄像头的预览
//                                camera.release();//释放资源
//                                camera = null;//取消原来摄像头
//                                camera = Camera.open(i);//打开当前选中的摄像头
//                                camera.setDisplayOrientation(90);
//                                try {
//                                    camera.setPreviewDisplay(sv.getHolder());//通过surfaceview显示取景画面
//                                } catch (IOException e) {
//                                    e.printStackTrace();
//                                }
//                                camera.startPreview();//开始预览
//                                cameraPosition = 1;
//                                break;
//                            }
//                        }
//
//                    }
//                }
//
//            }
//        }
//    }

    public void onclick_menu(View view) {
        //分享图片相关操作
        if (view.getId() == R.id.ig_remake) {
            //重新拍照
            camera.startPreview();
            fl.setVisibility(View.VISIBLE);
            fl_new.setVisibility(View.INVISIBLE);
//        ig_new.setBackground(Drawable.createFromPath(picUrl));
            rl_menu.setVisibility(View.VISIBLE);
            rl_share_menu.setVisibility(View.INVISIBLE);

        } else {
            //代码  有待优化
            showShareChoose();
        }
    }

    //显示分享选项
    public void showShareChoose() {
        rl_share_choose.setVisibility(View.VISIBLE);
        rl_share_menu.setVisibility(View.INVISIBLE);
    }


    public void share_chose(View view) {
        int id = view.getId();
        if (id == R.id.ig_weibo) {
            weiBoShare(getString(R.string.showPic_title), imgUrl_share);
        } else {
            Toast.makeText(this, "weixin", Toast.LENGTH_SHORT).show();
            weiXinWebShare(false, this, new String[]{"测试微信图片分享", imgUrl_share});
        }
    }

    //微博分享（图片分享）
    public void weiBoShare(String title, String imagePath) {
        Platform wb = ShareSDK.getPlatform(SinaWeibo.NAME);
        Platform.ShareParams sp = new SinaWeibo.ShareParams();
        sp.setTitle(title);
        sp.setImagePath(imagePath);
        wb.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Utils.showToast(getString(R.string.share_success));

            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Utils.showToast(getString(R.string.share_failed));
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Utils.showToast(getString(R.string.share_cancle));
            }
        });
        wb.share(sp);

    }


    private Context context;

    //微信分享(图片分享)
    public void weiXinWebShare(boolean isWeixin, Context mContext, String... args) {
        if (null == mContext || args.length < 1) {
//            MainApplication.getIns().tip('分享失败');
            return;
        } else {
            this.context = mContext;
            for (int i = 0; i < args.length; i++) {
                String str = args[i];
                if (TextUtils.isEmpty(str) && i != 2) {
//                    MainApplication.getIns().tip('分享失败');分享失败
                    return;
                }
            }
            String title = args[0];
            String image = args[1];
            WechatHelper.ShareParams sp = null;
            if (isWeixin) {
                sp = new Wechat.ShareParams();
            } else {
                sp = new WechatMoments.ShareParams();
            }
            sp.title = title;

            if (TextUtils.isEmpty(image)) {
                sp.imageData = ((BitmapDrawable) context.getResources().getDrawable(R.drawable.biankuang)).getBitmap();
            } else {
                sp.imageData = BitmapFactory.decodeFile(image);
            }

            sp.setShareType(Platform.SHARE_IMAGE);
            Platform plat = null;
            if (isWeixin) {
                plat = ShareSDK.getPlatform(Wechat.NAME);
            } else {
                plat = ShareSDK.getPlatform(WechatMoments.NAME);
            }
            plat.setPlatformActionListener(new PlatformActionListener() {
                @Override
                public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                    Utils.showToast(getString(R.string.share_success));
                }

                @Override
                public void onError(Platform platform, int i, Throwable throwable) {
                    Utils.showToast(getString(R.string.share_failed));
                }

                @Override
                public void onCancel(Platform platform, int i) {
                    Utils.showToast(getString(R.string.share_cancle));
                }
            });
            plat.share(sp);
        }
    }

    private Bitmap bitmap;
    //拍照后调用的接口
    private final class TakePictureCallback implements Camera.PictureCallback {
        public void onPictureTaken(byte[] data, Camera camera) {
            try {
                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                bitmap = Utils.rotateBitmapByDegree(bitmap, 90);
                File dir = new File(Constans.PIC_SHARE);
//                ig_new.setImageBitmap(bitmap);
                if (!dir.exists()) {
                    dir.mkdir();
                    LogUtils.log_E("not exists");
                }
                String picUrl = Constans.PIC_SHARE + "/" + System.currentTimeMillis() + ".jpg";
                File file = new File(picUrl);
                FileOutputStream outputStream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
//                outputStream.write(data);
                outputStream.close();
                camera.stopPreview();
//                getPic(Environment.getExternalStorageDirectory() + "/");


//                getPic(Environment.getExternalStorageDirectory() + "/");
                imgUrl_share = picUrl;
                prepareShare(picUrl,bitmap);
//                camera.startPreview();//处理完数据之后可以预览
            } catch (Exception e) {
                Log.e("hu", e.toString()+"testprepared");
            }
        }
    }
    //压缩图片
    private static Bitmap small(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(0.5f, 0.5f); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
        return resizeBmp;
    }
    //指定大小对图片进行压缩

    public static Drawable resizeImage(Bitmap bitmap, int w, int h)
    {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        float n=scaleHeight>scaleWidth?scaleHeight:scaleWidth;

        Matrix matrix = new Matrix();
        matrix.postScale(n, n);
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return new BitmapDrawable(resizedBitmap);
    }
















    //准备分享
    public void prepareShare(String picUrl,Bitmap bit) {
        ImageView ig_back= (ImageView) findViewById(R.id.ig_back);
//        Bitmap b=BitmapFactory.decodeFile(picUrl);
//
//        b=small(b);
//        ig_new.setImageDrawable(resizeImage(b,Utils.dip2px(this,fl_new.getWidth()),Utils.dip2px(this,fl_new.getHeight())));


        switch (position){
            case 0:
                ig_back.setBackgroundResource(R.drawable.border1);
                break;
            case 1:
                ig_back.setBackgroundResource(R.drawable.border2);
                break;
            case 2:
                ig_back.setBackgroundResource(R.drawable.border3);
                break;
        }
//        fl.setVisibility(View.INVISIBLE);
//        fl_new.setVisibility(View.VISIBLE);
        rl_menu.setVisibility(View.INVISIBLE);
        rl_share_menu.setVisibility(View.VISIBLE);
//        getPic(imgUrl_share);
        myShot(this);
    }























    //将界面上的控件转化为图片
    public void getPic(String picPath) {
        View view = findViewById(R.id.fl_new); //获取布局控件属性
        final Bitmap bmp = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bmp);
        view.draw(canvas);
        final String photoUrl = picPath;//换成自己的图片保存路径
        final File file = new File(photoUrl);
        new Thread() {
            @Override
            public void run() {

                boolean bitMapOk = false;
                try {
                    bitMapOk = bmp.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    LogUtils.log_E("getpic======="+e.toString());
                }
                if (bitMapOk) {
                    LogUtils.log_E("success");
                }

            }
        }.start();

    }
    //屏幕截图
    public void getPicFrom() {
        //将布局转换为View类型对象
        View view = findViewById(R.id.fl);
        //打开图像缓存
        view.setDrawingCacheEnabled(true);
        //必须调用measure和layout方法才能成功保存可视组件的截图到png图像文件
        //测量View大小
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        //发送位置和尺寸到View及其所有的子View
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        try {
            //获得可视组件的截图
            Bitmap bitmap = view.getDrawingCache();
            //将截图保存在SD卡根目录的test.png图像文件中
            FileOutputStream fos = new FileOutputStream("/sdcard/test.png");
            //将Bitmap对象中的图像数据压缩成png格式的图像数据，并将这些数据保存在test.png文件中
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            //关闭文件输出流
            fos.close();
        } catch (Exception e) {

        }
    }

    //截屏
    private void screenshot() {
        // 获取屏幕
        View dView = getWindow().getDecorView();
        dView.setDrawingCacheEnabled(true);
        dView.buildDrawingCache();
        Bitmap bmp = dView.getDrawingCache();
        if (bmp != null) {
            try {
                // 获取内置SD卡路径
                String sdCardPath = Environment.getExternalStorageDirectory().getPath();
                // 图片文件路径
                String filePath = sdCardPath + File.separator + "screenshot.png";

                File file = new File(filePath);
                FileOutputStream os = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
                os.flush();
                os.close();
            } catch (Exception e) {
            }
        }
    }

    //回退事件
    @Override
    public void onBackPressed() {
        if (rl_share_choose.getVisibility() == View.VISIBLE) {
            rl_share_choose.setVisibility(View.INVISIBLE);
            rl_share_menu.setVisibility(View.VISIBLE);
        } else {
            finish();
        }
    }








    private Camera.Parameters parameters;
    //相机参数的初始化设置
    private void initCamera()
    {
        parameters=camera.getParameters();
        parameters.setPictureFormat(PixelFormat.JPEG);
        //parameters.setPictureSize(surfaceView.getWidth(), surfaceView.getHeight());  // 部分定制手机，无法正常识别该方法。
//        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//1连续对焦
        setDispaly(parameters, camera);
        camera.setParameters(parameters);
        if(!isPreview){
            camera.startPreview();
        }
        camera.cancelAutoFocus();// 2如果要实现连续的自动对焦，这一句必须加上

    }

    //控制图像的正确显示方向
    private void setDispaly(Camera.Parameters parameters,Camera camera)
    {
        if (Integer.parseInt(Build.VERSION.SDK) >= 8){
            setDisplayOrientation(camera, 90);
        }
        else{
            parameters.setRotation(90);
        }

    }

    //实现的图像的正确显示
    private void setDisplayOrientation(Camera camera, int i) {
        Method downPolymorphic;
        try{
            downPolymorphic=camera.getClass().getMethod("setDisplayOrientation", new Class[]{int.class});
            if(downPolymorphic!=null) {
                downPolymorphic.invoke(camera, new Object[]{i});
            }
        }
        catch(Exception e){
            Log.e("Came_e", "图像出错");
        }









    }

    //退出 返回
    public void close(View view){
        if (rl_share_choose.getVisibility() == View.VISIBLE) {
            rl_share_choose.setVisibility(View.INVISIBLE);
            rl_share_menu.setVisibility(View.VISIBLE);
        } else {
            finish();
        }
    }



    private Bitmap mScreenBitmap;
    public void getView_screen(){
//        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
//        float[] dims = { mDisplayMetrics.widthPixels,
//                mDisplayMetrics.heightPixels };
//        Class<?> demo = null;
//        try {
//            demo = Class.forName("android.view.Surface");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        try{
//            Method method=demo.getMethod("interceptScreenshotChord",new Class[]{int.class,int.class});
//            mScreenBitmap = (Bitmap) method.invoke(demo.newInstance(),(int) dims[0],(int) dims[1]);
//            //这里其实可以直接用null替换demo.newInstance()，因为screenshot是静态方法，所以第一个invoke的第一个参数会被自动忽略~所以其实你填什么都没关系。
//            //获取的返回值是个bitmap，然后我们就可以为所欲为了~
//            String picUrl = Constans.PIC_SHARE + "/" + System.currentTimeMillis() + ".jpg";
//            File file = new File(picUrl);
//            FileOutputStream outputStream = new FileOutputStream(file);
//            mScreenBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
////                outputStream.write(data);
//            outputStream.close();
//        }catch (Exception e) {
//            e.printStackTrace();
//            LogUtils.log_E(e.toString());
//        }






    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
    }








    public Bitmap myShot(Activity activity) {
    // 获取windows中最顶层的view
        View view = activity.getWindow().getDecorView();
        view.buildDrawingCache();
    // 获取状态栏高度
        Rect rect = new Rect();
        view.getWindowVisibleDisplayFrame(rect);
        int statusBarHeights = rect.top;
            Display display = activity.getWindowManager().getDefaultDisplay();
    // 获取屏幕宽和高
        int widths = display.getWidth();
        int heights = display.getHeight();
// 允许当前窗口保存缓存信息
        view.setDrawingCacheEnabled(true);
// 去掉状态栏
        Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(), 0,
                statusBarHeights, widths, heights-statusBarHeights);
// 销毁缓存信息
        view.destroyDrawingCache();
        String picUrl = Constans.PIC_SHARE + "/" + System.currentTimeMillis() + ".jpg";
        File file = new File(picUrl);
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
//                outputStream.write(data);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bmp;
    }









}
